<?php
/**
 * Created by PhpStorm.
 * User: cx
 * Date: 2019-01-08
 * Time: 19:06
 */

namespace services\api;

use yii\filters\auth\HttpHeaderAuth;

class BaseHeaderAuth extends HttpHeaderAuth
{
    public static $authHeader;
    /**
     * @var string the HTTP header name
     */
    public $header = 'X-Api-Key';
    /**
     * @var string a pattern to use to extract the HTTP authentication value
     */
    public $pattern;

    /**
     * {@inheritdoc}
     */
    public function authenticate($user, $request, $response)
    {
        $authHeader = $request->getHeaders()->get($this->header);

        if ($authHeader !== null) {
            if ($this->pattern !== null) {
                if (preg_match($this->pattern, $authHeader, $matches)) {
                    $authHeader = $matches[1];
                } else {
                    return null;
                }
            }
            self::$authHeader = $authHeader;
            return true;
        }

        return null;
    }

    public function behaviors()
    {
        $behaviors=parent::behaviors();
        //移去身份验证过滤器
        $auth=$behaviors['authenticator'];
        unset($behaviors['authenticator']);
        //添加CORS过滤器
        $behaviors['corsFilter']=[
            'class'	=>\yii\filters\Cors::className(),
        ];
        //重新添加身份验证过滤器
        $behaviors['authenticator']=$auth;
        //在CORS-pre-flight请求中避免使用身份验证(HTTP OPTIONS方法)
        $behaviors['authenticator']['except']=['options'];
        return $behaviors;
    }
}